package com.ruoyi.web.controller.mail;

import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/mail")
public class MailController {


    @Autowired
    private MailService mailService;


    @Autowired
    private TemplateService templateService;

 // 免登录注解
    // 发送文本邮件
    @PostMapping("/text")
    public String sendTextMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content) {
        mailService.sendText(to, subject, content);
        return "Text mail sent!";
    }

    // 发送HTML邮件（支持模板）
    @PostMapping("/html")
    public String sendHtmlMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestBody String htmlContent) {
        mailService.sendHtml(to, subject, htmlContent);
        return "HTML mail sent!";
    }

    // 发送带附件的邮件
    @PostMapping("/attachment")
    public String sendAttachmentMail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content,
            @RequestParam List<String> attachmentPaths) {
        List<File> files = attachmentPaths.stream()
                .map(FileUtil::file)
                .toList();
        mailService.sendWithAttachments(to, subject, content, files);
        return "Mail with attachments sent!";
    }

    @PostMapping("/template")
    public String sendTemplateMail(
            @RequestParam String to,
            @RequestParam String name,
            @RequestParam String code) {
        Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("code", code);
        String html = templateService.renderTemplate("templates/mail.html", params);
        mailService.sendHtml(to, "模板邮件", html);
        return "Template mail sent!";
    }

}
